package com.example.scaffolding.ui.user

import android.content.Context
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.scaffolding.db.DataBaseInstance
import com.example.scaffolding.db.bean.User
import com.example.scaffolding.db.dao.UserDao
import org.junit.Assert.assertFalse
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class UserViewModelTest() {
    private lateinit var context: Context
    private lateinit var userViewModel: UserViewModel
    private lateinit var dao: UserDao

    @get:Rule
    var instantExecutorRule = InstantTaskExecutorRule()

    @Before
    fun setUp() {
        context = ApplicationProvider.getApplicationContext<Context>()
        dao = DataBaseInstance.getINSTANCE(context).userDao()
        userViewModel = UserViewModel(dao)
    }

    @Test
    fun getUsers_loadUsersEvent() {

        val observer = Observer<List<User>> {}
        userViewModel.users.observeForever(observer)
        try {
            dao.insert(User().apply {
                id = 0
                name = "Poly"
                type = 0
                url = "http://"
            })

            dao.insert(User().apply {
                id = 1
                name = "Mike"
                type = 1
                url = "http://"
            })

            val list = userViewModel.users.value

            println("list: $list")
            assertFalse(list.isNullOrEmpty())

        } finally {
            userViewModel.users.removeObserver(observer)
        }
    }
}